#include "objcon.h"

struct vertex_t
{
	float p[3];
	float n[3];
	float t[2];
};

struct material_t
{
	float ambient[4];
	float diffuse[4];
	float specular[4];
	float emission[4];
	float shininess;
};

struct mesh_t
{
	struct head_t
	{
		uint32_t vcount;
		uint32_t icount;
		uint32_t scount;
		uint32_t vtype;
	} head;

	struct subset_t
	{
		uint32_t ioffset;
		uint32_t icount;
	} subsets[16];
};

int main(int argc, char *argv[])
{
	if (argc < 3)
	{
		fprintf(stderr, "Usage: objcon.exe <obj> <out>\n");
		return 1;
	}

	obj_t *obj = obj_parse_file(argv[1]);

	if (obj == NULL)
		return 2;

	assert(obj->mesh.head.vsize == 32);
	assert(obj->mesh.head.vtype == OBJ_P3F_N3F_T2F);
	assert(obj->mesh.head.scount > 0 && obj->mesh.head.scount <= 16);
	assert(obj->mesh.head.mcount <= 16);

	mesh_t   mesh;
	uint32_t i;

	memset(&mesh, 0, sizeof(mesh_t));

	mesh.head.vcount = obj->mesh.head.vcount;
	mesh.head.icount = obj->mesh.head.icount;
	mesh.head.scount = obj->mesh.head.scount;
	mesh.head.vtype  = obj->mesh.head.vtype;

	for (i = 0; i < mesh.head.scount; ++i)
	{
		mesh.subsets[i].ioffset = obj->mesh.subsets[i].ioffset;
		mesh.subsets[i].icount  = obj->mesh.subsets[i].icount;
	}

	FILE *output = fopen(argv[2], "wb");
	if (output == NULL)
	{
		fprintf(stderr, "Cant open output file %s\n", argv[2]);
		obj_destroy(obj);
		return 3;
	}

	printf("%s saving begin...\n", argv[2]);

	fwrite(&mesh, sizeof(mesh_t), 1, output);
	fwrite(obj->mesh.vdata, sizeof(vertex_t), mesh.head.vcount, output);
	fwrite(obj->mesh.idata, sizeof(uint32_t), mesh.head.icount, output);

	printf("%s saving end\n", argv[2]);

	obj_destroy(obj);
	return 0;
}
